﻿using System;
using System.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
using umbraco.cms.businesslogic;
using umbraco.interfaces;
using ClientDependency.Core.Controls;
using ClientDependency.Core;

using System.Web;
using umbraco.cms.businesslogic.web;


using System.Collections.Generic;
using System.Linq;

namespace umbraco.editorControls.multiuserpicker
{
    [ValidationProperty("IsValid")]
    public class multiuserpickerDataEditor : UpdatePanel, IDataEditor
    {
        private IData _data;
        string _configuration;

        private string[] config;
        private string controlType;
        private string userType;

        private string[] dataValues;

        private TextBox childtxt;
        private DropDownList dropdownlistNodes;
        private CheckBoxList checkboxlistNodes;
        private RadioButtonList radiobuttonlistNodes;
        private ListBox listboxNodes;
        private Button clearRadiobuttonlist;
        private CheckBox clearRadiobuttons;

        public multiuserpickerDataEditor(umbraco.interfaces.IData Data, string Configuration)
        {
            _data = Data;
            _configuration = Configuration;

            config = _configuration.Split("|".ToCharArray());
            controlType = config[0];
            userType = config[1];

            RenderMode = UpdatePanelRenderMode.Inline;
        }

        public virtual bool TreatAsRichTextEditor
        {
            get { return false; }
        }

        public bool ShowLabel
        {
            get { return true; }
        }

        /// <summary>
        /// Internal logic for validation controls to detect whether or not it's valid (has to be public though) 
        /// </summary>
        /// <value>Am I valid?</value>
        public string IsValid
        {
            get
            {
                switch (controlType.ToLower())
                {
                    case "checkboxlist":
                        foreach (ListItem item in checkboxlistNodes.Items)
                        {
                            if (item.Selected)
                            {
                                return "valid";
                            }
                        }
                        break;
                    case "dropdownlist":
                        return dropdownlistNodes.SelectedValue;
                    case "listbox":
                        foreach (ListItem item in listboxNodes.Items)
                        {
                            if (item.Selected)
                            {
                                return "valid";
                            }
                        }
                        break;
                    case "radiobuttonlist":
                        foreach (ListItem item in radiobuttonlistNodes.Items)
                        {
                            if (item.Selected)
                            {
                                return "valid";
                            }
                        }

                        break;

                }
                return "";
            }
        }

        public Control Editor { get { return this; } }

        public void Save()
        {
            string dataToSave = string.Empty;

            switch (controlType)
            {
                case "CheckBoxList":

                    foreach (ListItem item in checkboxlistNodes.Items)
                    {
                        if (item.Selected)
                        {
                            dataToSave += item.Value + ",";
                        }
                    }

                    if (dataToSave.Length > 0)
                    {
                        dataToSave = dataToSave.Substring(0, dataToSave.Length - 1);
                    }


                    break;
                case "checkbox":
                    goto case "CheckBoxList";
                case "DropDownList":
                    dataToSave = dropdownlistNodes.SelectedValue;
                    break;
                case "dropdown":
                    goto case "DropDownList";
                case "ListBox":
                    dataToSave = string.Empty;
                    foreach (ListItem item in listboxNodes.Items)
                    {
                        if (item.Selected)
                        {
                            dataToSave += item.Value + ",";
                        }
                    }

                    if (dataToSave.Length > 0)
                    {
                        dataToSave = dataToSave.Substring(0, dataToSave.Length - 1);
                    }
                    break;
                case "listbox":
                    goto case "ListBox";
                case "RadioButtonList":
                    dataToSave = string.Empty;

                    if (!clearRadiobuttons.Checked)
                    {
                        foreach (ListItem item in radiobuttonlistNodes.Items)
                        {
                            if (item.Selected)
                            {
                                dataToSave += item.Value + ",";
                            }
                        }

                        if (dataToSave.Length > 0)
                        {
                            dataToSave = dataToSave.Substring(0, dataToSave.Length - 1);
                        }
                    }
                    else
                    {
                        foreach (ListItem radiobutton in radiobuttonlistNodes.Items)
                        {
                            radiobutton.Selected = false;
                        }

                        clearRadiobuttons.Checked = false;
                    }

                    break;
                case "radiobox":
                    goto case "RadioButtonList";

            }
            if (controlType != "auto-suggest" && controlType != "AutoComplete")
            {
                this._data.Value = dataToSave;

            }
            else
            {
                if (dataToSave.Length > 0)
                {
                    this._data.Value = dataToSave;
                }else
                {
                    if (childtxt.Text.Trim().Length == 0)
                    {
                        this._data.Value = "";
                    }
                }
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            try
            {
                string[] datavalues = _data.Value.ToString().Split(",".ToCharArray());

                switch (controlType)
                {
                    case "CheckBoxList":
                        checkboxlistNodes = new CheckBoxList();
                        //checkboxlistNodes.ID = "nodes";
                       
                        

                         checkboxlistNodes.AutoPostBack = true;
                         //checkboxlistNodes.SelectedIndexChanged += new EventHandler(checkboxlistNodes_SelectedIndexChanged);

                         addListControlNode(1, checkboxlistNodes);


                        base.ContentTemplateContainer.Controls.Add(checkboxlistNodes);

                        break;
                    case "checkbox":
                        goto case "CheckBoxList";
                    case "DropDownList":
                        dropdownlistNodes = new DropDownList();
                        //dropdownlistNodes.ID = "nodes";
                        ListItem empty = new ListItem("");
                        dropdownlistNodes.Items.Add(empty);
                        addListControlNode(1, dropdownlistNodes);
                        foreach (string datavalue in datavalues)
                        {
                            dropdownlistNodes.SelectedValue = datavalue;
                        }
                        base.ContentTemplateContainer.Controls.Add(dropdownlistNodes);
                        break;
                    case "dropdown":
                        goto case "DropDownList";
                    case "ListBox":
                        listboxNodes = new ListBox();
                        //listboxNodes.ID = "nodes";
                        listboxNodes.SelectionMode = ListSelectionMode.Multiple;
                        listboxNodes.Width = 300;
                        listboxNodes.Height = 200;

                        addListControlNode(1, listboxNodes);
                        base.ContentTemplateContainer.Controls.Add(listboxNodes);
                        break;
                    case "listbox":
                        goto case "ListBox";
                    case "RadioButtonList":
                        radiobuttonlistNodes = new RadioButtonList();
                        radiobuttonlistNodes.AutoPostBack = true;
                        radiobuttonlistNodes.SelectedIndexChanged += new EventHandler(radiobuttonlistNodes_SelectedIndexChanged);
                        //radiobuttonlistNodes.ID = "nodes";
                        addListControlNode(1, radiobuttonlistNodes);

                        clearRadiobuttonlist = new Button();
                        clearRadiobuttonlist.Click += new EventHandler(clearRadiobuttonlist_Click);
                        clearRadiobuttonlist.Text = "Clear";

                        clearRadiobuttons = new CheckBox();
                        clearRadiobuttons.Visible = false;

                        base.ContentTemplateContainer.Controls.Add(radiobuttonlistNodes);
                        base.ContentTemplateContainer.Controls.Add(clearRadiobuttonlist);
                        base.ContentTemplateContainer.Controls.Add(clearRadiobuttons);
                        break;
                    case "radiobox":
                        goto case "RadioButtonList";
                }
            }
            catch { }
        }

        //void checkboxlistNodes_SelectedIndexChanged(object sender, EventArgs e)
        //{
        //    Boolean editSelect = false;
        //    Boolean selectValue;

        //    checkboxlistNodes.

        //    foreach (ListItem chechbox in checkboxlistNodes.Items)
        //    {
        //        if (chechbox.Text.Contains("<u>"))
        //        {
        //            selectValue = chechbox.Selected;
        //        }
        //        else
        //        {
        //            if (editSelect)
        //            {

        //            }
        //        }
        //    }
        //}

        void radiobuttonlistNodes_SelectedIndexChanged(object sender, EventArgs e)
        {
            clearRadiobuttons.Checked = false;
        }

        void clearRadiobuttonlist_Click(object sender, EventArgs e)
        {
           

            foreach (ListItem radiobutton in radiobuttonlistNodes.Items)
            {
                radiobutton.Selected = false;
            }

            clearRadiobuttons.Checked = true;
        }


        /// <summary>
        /// Adds sub nodes to the ListControl object passed into the method, based on the Content node passed in
        /// </summary>
        /// <param name="level">The level of the current node</param>
        /// <param name="control">The ListControl the nodes must be added to</param>
        //private void addListControlNode(umbraco.BusinessLogic.UserType userType, int level, bool showGrandChildren, ListControl control, string[] documentAliasFilters)
        private void addListControlNode(int level, ListControl control)
        {
            List<umbraco.BusinessLogic.UserType> lstTypes;
            if (userType.Length > 0)
            {
                lstTypes = umbraco.BusinessLogic.UserType.GetAllUserTypes().Where(u => u.Name == userType).ToList<umbraco.BusinessLogic.UserType>();
            }
            else
            {
                lstTypes = umbraco.BusinessLogic.UserType.getAll.ToList<umbraco.BusinessLogic.UserType>();
            }
            

            
            //checkboxlistNodes = new CheckBoxList();

            
            foreach (umbraco.BusinessLogic.UserType usrType in lstTypes)
            {
                List<umbraco.BusinessLogic.User> lst = umbraco.BusinessLogic.User.getAll().Where(u => u.UserType == usrType).ToList<umbraco.BusinessLogic.User>();

                if (lst.Count > 0)
                {
                    //Label lblTitel = new Label();
                    //lblTitel.Text = "<u>" + usrType.Name + "</u><br />";
                    //base.ContentTemplateContainer.Controls.Add(lblTitel);
                    ListItem itemBase = new ListItem("<u>" + usrType.Name + "</u>", usrType.Id.ToString());
                    //itemBase.Attributes.CssStyle["display"] = "none";
                    itemBase.Enabled = false;
                    control.Items.Add(itemBase);
                    //control.Items.Clear();

                    foreach (umbraco.BusinessLogic.User usr in lst)
                    {
                        //string preText = string.Empty;

                        ListItem item = new ListItem("&nbsp;&nbsp;&nbsp;<b>" + usr.Name + "</b>", usr.Id.ToString());
                        if (_data.Value.ToString().Contains(usr.Id.ToString()))
                        {
                            item.Selected = true;
                        }
                        control.Items.Add(item);
                    }
                    //base.ContentTemplateContainer.Controls.Add(control);
                }
                
            }
                //.ToList<umbraco.BusinessLogic.UserType>();
            //List<umbraco.BusinessLogic.User> lst = umbraco.BusinessLogic.User.getAll().Where(u => u.UserType == userType).ToList<umbraco.BusinessLogic.User>();

            



            //if (node.HasChildren)
            //{
            //    //store children array here because iterating over an Array property object is very inneficient.
            //    var c = node.Children;
            //    foreach (CMSNode child in c)
            //    {
            //        umbraco.cms.businesslogic.Content doc = new umbraco.cms.businesslogic.Content(child.Id);
            //        string preText = string.Empty;

            //        for (int i = 1; i < level; i++)
            //        {
            //            preText += "- ";
            //        }

            //        //Run through the filters passed in
            //        if (documentAliasFilters.Length > 0)
            //        {
            //            foreach (string filter in documentAliasFilters)
            //            {
            //                string trimmedFilter = filter.TrimStart(" ".ToCharArray());
            //                trimmedFilter = trimmedFilter.TrimEnd(" ".ToCharArray());

            //                if (doc.ContentType.Alias == trimmedFilter || trimmedFilter == string.Empty)
            //                {
            //                    ListItem item = new ListItem(preText + "<a href=editContent.aspx?id=" + doc.Id.ToString() + "#>" + doc.Text + "</a>", doc.Id.ToString());
            //                    if (_data.Value.ToString().Contains(doc.Id.ToString()))
            //                    {
            //                        item.Selected = true;
            //                    }
            //                    control.Items.Add(item);
            //                }
            //            }
            //        }
            //        else
            //        {
            //            ListItem item = new ListItem(preText + "<a href=editContent.aspx?id=" + doc.Id.ToString() + "#>" + doc.Text + "</a>", doc.Id.ToString());
            //            if (_data.Value.ToString().Contains(doc.Id.ToString()))
            //            {
            //                item.Selected = true;
            //            }
            //            control.Items.Add(item);
            //        }

            //        if (showGrandChildren)
            //        {
            //            addListControlNode(doc, level + 1, showGrandChildren, control, documentAliasFilters);
            //        }
            //    }
            //}
        }
     
    }
}
